from apps.interface.pageConfig.baseViews import *
from apps.interface.client.dao import ClientDao
from apps.interface.advert.serializers import Advert, AdvertBaseSerializer
from apps.interface.pageConfig.data import minePageConfig
from apps.user.dao import UserDao
from project.settings import build

class PageConfigViewSet(BasePageConfigViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = PageConfigDao().findAll().select_related('pagee').prefetch_related('clients')
        if self.request.user.role.key == '供应链':
            return _list.filter(Q(id = 1) | Q(id = 83) | Q(id = 84))
        return _list.order_by('-isRoot', 'id')

    '''根据终端获取界面配置'''
    @action(methods=['post'], detail=False, authentication_classes = [], permission_classes = [])
    def getPageConfigByClientname(self, request):
        params = getRequestParams(request)
        _pageConfig = None
        if params.get('pageConfigId'):
            _pageConfig = PageConfigDao().findOneByObjId(params.get('pageConfigId'))
        else:
            _client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
            _pageConfigs = PageConfigDao().findAll().filter(pagee__name=params.get('name'), clients__in=[_client]).exclude(key='custom')
            if _client:
                if _client.checking and params.get('build') == str(build) and params.get('name') == 'home':
                    _pageConfigs = PageConfigDao().findAll().filter(pagee__name='home2', clients__in=[_client]).exclude(key='custom')
            if _pageConfigs.exists():
                _pageConfig = _pageConfigs.first()
        if not _pageConfig:
            return Response(response_error('界面不存在'))
        return Response(response_success(PageConfigDetailSerializer(_pageConfig).data))

    
    '''更新信息'''
    @action(methods=['post'], detail=False)
    def updatePageConfig(self, request):
        params = getRequestParams(request)
        _advertList = params.get('advertList')
        if type(_advertList) == list:
            for advert in _advertList:
                if advert.get('id'):
                    serializers = AdvertBaseSerializer(Advert.objects.get(id=advert.get('id')), data=advert, partial=True)
                    if serializers.is_valid():
                        serializers.save()
                    else:
                        print(serializers.errors)
        PageConfigDao().update(params.get('pageConfigId'), params)
        return Response(response_success('更新成功'))
    
    '''获取个人中心配置数据'''
    @action(methods=['post'], detail=False, authentication_classes = [], permission_classes = [])
    def getMinePageConfig(self, request):
        params = getRequestParams(request)
        _userId = params.get('userId')
        itemList = []
        if _userId:
            _user = UserDao().findOneByObjId(_userId)
            shops = _user.user_shop.all()
            if shops.count() > 0:
                if shops.count() > 1:
                    return Response(response_message('您的商户异常，请联系管理员'))
                elif shops.count() == 1:
                    shop = shops.first()
                    if shop.checkStatus == 'PASS':
                        item = {
                                    'title': "商家中心",
                                    'icon': 'grid',
                                    'color': '#2b85e4',
                                    'name': 'businessCenter',
                                    'size': '26',
                                }
                        itemList.append(item)
        itemList = itemList + minePageConfig.config
        itemListConfig = [{'title': '常用功能', 'items': itemList}, {'title': '其他功能', 'items': minePageConfig.config2}, ]
        client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
        if client.checking and params.get('build') == str(build):
            itemListConfig = itemListConfig = [{'title': '其他功能', 'items': minePageConfig.config2}, ]
        return Response(response_success({'itemListConfig': itemListConfig}))

    '''获取个人中心私有配置数据'''
    @action(methods=['post'], detail=False)
    def getMinePageConfigForPrivate(self, request):
        params = getRequestParams(request)
        configs = []
        if self.request.user.rank.grade >= 1:
            config = {
                        'title': "我的团队",
                        'icon': '/static/common/mine/duoshou.png',
                        'color': '#999',
                        'name': 'duoshou',
                        'size': '26',
                    }
            configs.append(config)
        
        shops = self.request.user.user_shop.all()
        if shops.count() > 0:
            if shops.count() > 1:
                return Response(response_message('您的商户异常，请联系管理员'))
            elif shops.count() == 1:
                shop = shops.first()
                if shop.checkStatus == 'PASS':
                    config = {
                                'title': "商家中心",
                                'icon': '/static/common/mine/duoshou.png',
                                'color': '#999',
                                'name': 'businessCenter',
                                'size': '26',
                            }
                    configs.append(config)
        client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
        return Response(response_success({'title': '', 'items': configs}))
